#include "net_command_handler.h"
#include "utils_log.h"
#include <chrono>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include "common_version.h"
#include "common_product_definition.h"
#include "common_config_manager.h"
#include "network.h"
#include "utils_task.h"

namespace El {
namespace Protocol {

void NetCommandHandler::RegisterMethodHandlers(
    std::unordered_map<std::string, std::function<nlohmann::json(const std::string &, const nlohmann::json &)>>
        &handlers)
{
    // 注册设备信息获取方法
    handlers["network.getConfig"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleNetworkGetConfig(id, params);
    };

    // 注册修改网卡配置方法
    handlers["network.setConfig"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleNetworkSetConfig(id, params);
    };

    // 更新dns配置方法
    handlers["network.updateDNS"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleNetworkUpdateDNS(id, params);
    };

    // 获取GB28181配置方法
    handlers["gb28181.getConfig"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleGB28181GetConfig(id, params);
    };

    // 设置GB28181配置方法
    handlers["gb28181.setConfig"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleGB28181SetConfig(id, params);
    };

    // 获取RTMP推流配置
    handlers["rtmp.getConfig"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleRTMPGetConfig(id, params);
    };

    // 设置RTMP推流配置
    handlers["rtmp.setConfig"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleRTMPSetConfig(id, params);
    };

    // 获取RTMP运行状态
    handlers["rtmp.getStatus"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleRTMPGetStatus(id, params);
    };

    // 获取RTSP服务配置
    handlers["rtsp.getConfig"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleRTSPGetConfig(id, params);
    };

    // 设置RTSP服务配置
    handlers["rtsp.setConfig"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleRTSPSetConfig(id, params);
    };
}

nlohmann::json NetCommandHandler::HandleNetworkGetConfig(const std::string &id, const nlohmann::json &params)
{
    EL_DEBUG("处理network.getConfig请求, 参数: {}", params.dump());

    // 使用ConfigManager获取网络配置
    auto &configManager = Common::ConfigManager::GetInstance();
    nlohmann::json networkConfig = configManager.GetConfig("/network");
    if (networkConfig.is_null()) {
        return CreateErrorResponse(id, 404, "网络配置未找到");
    }

    // 构建符合协议规范的返回数据
    nlohmann::json result;

    // 添加默认网卡信息
    if (networkConfig.contains("default_interface")) {
        result["default_interface"] = networkConfig["default_interface"];
    } else {
        result["default_interface"] = "eth0"; // 默认值
    }

    // 添加接口信息
    if (networkConfig.contains("interfaces")) {
        result["interfaces"] = networkConfig["interfaces"];
    }

    // 添加dns
    if (networkConfig.contains("dns")) {
        result["dns"] = networkConfig["dns"];
    } else {
        result["dns"] = nlohmann::json::array(); // 默认值
    }

    // 添加主机名
    if (networkConfig.contains("hostname")) {
        result["hostname"] = networkConfig["hostname"];
    }

    return CreateSuccessResponse(id, result);
}

// 修改网卡配置
nlohmann::json NetCommandHandler::HandleNetworkSetConfig(const std::string &id, const nlohmann::json &params)
{
    EL_DEBUG("处理network.setConfig请求, 参数: {}", params.dump());

    // 参数验证
    if (!params.contains("interface_name") || !params.contains("mode")) {
        return CreateErrorResponse(id, 400, "缺少必要参数：interface_name或者mode");
    }

    std::string interfaceName = params["interface_name"];
    std::string mode = params["mode"];

    // 验证mode参数
    if ((mode != "dhcp" && mode != "static")) {
        return CreateErrorResponse(id, 400, "config.mode必须为dhcp或static");
    }

    nlohmann::json ipv4Config;
    // 静态IP模式需要验证必要参数
    if (mode == "static") {
        if (!params.contains("ipv4") || !params["ipv4"].is_object() || !params["ipv4"].contains("address") ||
            !params["ipv4"].contains("netmask") || !params["ipv4"].contains("gateway")) {
            return CreateErrorResponse(id, 400, "静态IP模式需要提供address、netmask和gateway参数");
        }
        ipv4Config = params["ipv4"]; // 保存ipv4配置供后续使用
    }

    // 使用ConfigManager获取网络配置
    auto &configManager = Common::ConfigManager::GetInstance();
    nlohmann::json networkConfig = configManager.GetConfig("/network");
    if (networkConfig.is_null()) {
        return CreateErrorResponse(id, 404, "网络配置未找到");
    }

    // 检查接口是否存在（允许新接口）
    if (networkConfig.contains("interfaces") && networkConfig["interfaces"].contains(interfaceName) &&
        (!networkConfig["interfaces"][interfaceName].contains("enable") ||
         !networkConfig["interfaces"][interfaceName]["enable"].get<bool>())) {
        EL_INFO("接口{}当前被禁用，将启用该接口", interfaceName);
    }

    // 使用 Utils::TaskScheduler 调度后台任务来应用网络配置
    Utils::TaskScheduler::GetInstance().PostTask("ApplyNetworkConfig", [interfaceName, mode, ipv4Config]() {
        EL_INFO("开始在后台应用网络配置: interface={}, mode={}", interfaceName, mode);
        auto &network = El::Network::Network::GetInstance();
        bool networkConfigApplied = false;

        if (mode == "dhcp") {
            networkConfigApplied = network.ConfigureNetworkDhcp(interfaceName);
            if (!networkConfigApplied) {
                EL_ERROR("后台应用DHCP网络配置失败: {}", interfaceName);
            } else {
                EL_INFO("后台应用DHCP网络配置成功: {}", interfaceName);
            }
        } else {
            // 静态IP模式配置
            std::string ipAddress = ipv4Config["address"];
            std::string netmask = ipv4Config["netmask"];
            std::string gateway = ipv4Config["gateway"];

            networkConfigApplied = network.ConfigureNetworkStatic(interfaceName, ipAddress, netmask, gateway);
            if (!networkConfigApplied) {
                EL_ERROR("后台应用静态IP网络配置失败: {}", interfaceName);
            } else {
                EL_INFO("后台应用静态IP网络配置成功: {}", interfaceName);
            }
        }
    });

    // 立即返回成功响应，表示请求已被接受并在后台处理
    EL_INFO("网络配置请求已接受，将在后台处理: {}", interfaceName);
    nlohmann::json result = {{"status", "success"}, {"message", "配置将在后台应用"}, {"requires_reboot", false}};
    return CreateSuccessResponse(id, result);
}

// 修改DNS配置
nlohmann::json NetCommandHandler::HandleNetworkUpdateDNS(const std::string &id, const nlohmann::json &params)
{
    EL_DEBUG("处理network.updateDNS请求, 参数: {}", params.dump());

    // 参数验证
    if (!params.contains("dns") || !params["dns"].is_array()) {
        return CreateErrorResponse(id, 400, "缺少必要参数：dns");
    }

    // 验证DNS服务器地址
    if (params["dns"].size() < 1 || params["dns"].size() > 2) {
        return CreateErrorResponse(id, 400, "DNS服务器地址数量必须为1或2");
    }

    // 获取DNS服务器列表
    auto &networkService = El::Network::Network::GetInstance();
    networkService.ConfigureDnsServers(params["dns"][0].get<std::string>(),
                                       params["dns"].size() > 1 ? params["dns"][1].get<std::string>() : "");

    // 构建响应
    nlohmann::json result = {{"status", "success"}, {"requires_reboot", false}};
    return CreateSuccessResponse(id, result);
}

// 获取GB28181配置
nlohmann::json NetCommandHandler::HandleGB28181GetConfig(const std::string &id, const nlohmann::json &params)
{
    EL_DEBUG("处理gb28181.getConfig请求, 参数: {}", params.dump());

    auto &configManager = Common::ConfigManager::GetInstance();
    nlohmann::json gb28181Config = configManager.GetConfig("/gb28181");

    // 返回完整配置对象（兼容旧数组格式）
    nlohmann::json result = nlohmann::json::object();
    result["enabled"] = true;
    result["sip_server"] = nlohmann::json::array();

    if (gb28181Config.is_object()) {
        result = gb28181Config;
        if (!result.contains("enabled")) {
            result["enabled"] = true;
        }
        if (!result.contains("sip_server") || !result["sip_server"].is_array()) {
            result["sip_server"] = nlohmann::json::array();
        }
    } else if (gb28181Config.is_array()) {
        result["sip_server"] = gb28181Config;
    }

    return CreateSuccessResponse(id, result);
}

// 设置GB28181配置
nlohmann::json NetCommandHandler::HandleGB28181SetConfig(const std::string &id, const nlohmann::json &params)
{
    EL_DEBUG("处理gb28181.setConfig请求, 参数: {}", params.dump());

    // 期望结构：{"enabled": bool, "sip_server": []}
    if (!params.is_object()) {
        return CreateErrorResponse(id, 400, "参数必须是对象格式");
    }

    bool enabled = params.value("enabled", true);

    if (!params.contains("sip_server") || !params["sip_server"].is_array()) {
        return CreateErrorResponse(id, 400, "缺少必要参数：sip_server");
    }

    const auto &servers = params["sip_server"];

    // 验证sip_server数组中的配置
    for (size_t i = 0; i < servers.size(); i++) {
        const auto &server = servers[i];
        if (!server.is_object()) {
            return CreateErrorResponse(id, 400, "sip_server[" + std::to_string(i) + "]配置必须是对象");
        }

        // 验证必要字段
        std::vector<std::string> required_fields = {"enabled",     "device_id", "server_id", "server_ip",
                                                    "server_port", "password",  "domain",    "civil_code"};

        for (const auto &field : required_fields) {
            if (!server.contains(field)) {
                return CreateErrorResponse(id, 400, "sip_server[" + std::to_string(i) + "]缺少必要参数：" + field);
            }
        }

        // 验证device_id和server_id格式（20位）
        std::string device_id = server["device_id"];
        std::string server_id = server["server_id"];
        if (device_id.length() != 20 || server_id.length() != 20) {
            return CreateErrorResponse(id, 400,
                                       "sip_server[" + std::to_string(i) + "]device_id和server_id必须是20位编码");
        }

        // 验证civil_code格式（6位）
        std::string civil_code = server["civil_code"];
        if (civil_code.length() != 6) {
            return CreateErrorResponse(id, 400, "sip_server[" + std::to_string(i) + "]civil_code必须是6位行政区划代码");
        }
    }

    nlohmann::json normalized = params;
    normalized["enabled"] = enabled;

    // 保存配置到配置管理器
    auto &configManager = Common::ConfigManager::GetInstance();
    if (!configManager.SetConfig("/gb28181", normalized)) {
        EL_ERROR("保存GB28181配置失败");
        return CreateErrorResponse(id, 500, "保存GB28181配置失败");
    }

    // 返回成功响应
    nlohmann::json result = {{"status", "success"}};
    return CreateSuccessResponse(id, result);
}

// 获取RTMP推流配置
nlohmann::json NetCommandHandler::HandleRTMPGetConfig(const std::string &id, const nlohmann::json &params)
{
    (void)params;
    EL_DEBUG("处理rtmp.getConfig请求");
    auto &configManager = Common::ConfigManager::GetInstance();
    nlohmann::json rtmp = configManager.GetConfig("/rtmp");

    // 若不存在，返回合理的默认结构
    if (rtmp.is_null() || !rtmp.is_object()) {
        rtmp = {{"enabled", false},
                {"sinks", nlohmann::json::array(
                              {nlohmann::json{{"enabled", false}, {"url", ""}, {"channel", 0}, {"stream_type", 0}}})}};
    }
    return CreateSuccessResponse(id, rtmp);
}

// 设置RTMP推流配置
nlohmann::json NetCommandHandler::HandleRTMPSetConfig(const std::string &id, const nlohmann::json &params)
{
    EL_DEBUG("处理rtmp.setConfig请求, 参数: {}", params.dump());

    if (!params.is_object()) {
        return CreateErrorResponse(id, 400, "参数必须为对象");
    }

    // 基本结构与类型检查
    if (!params.contains("enabled") || !params.contains("sinks") || !params["sinks"].is_array()) {
        return CreateErrorResponse(id, 400, "缺少必要参数：enabled 或 sinks");
    }

    // 校验 sinks
    for (size_t i = 0; i < params["sinks"].size(); ++i) {
        const auto &sink = params["sinks"][i];
        if (!sink.is_object()) {
            return CreateErrorResponse(id, 400, "sinks[" + std::to_string(i) + "] 必须是对象");
        }
        // 基本字段
        bool enabled = sink.value("enabled", false);
        std::string url = sink.value("url", "");
        int channel = sink.value("channel", 0);
        int stream_type = sink.value("stream_type", 0);

        if (enabled) {
            if (url.empty()) {
                return CreateErrorResponse(id, 400, "启用的目的地必须填写url");
            }
            // URL 必须以 rtmp:// 或 rtmps:// 开头
            if (!(url.rfind("rtmp://", 0) == 0 || url.rfind("rtmps://", 0) == 0)) {
                return CreateErrorResponse(id, 400, "url必须以rtmp://或rtmps://开头");
            }
        }
        if (channel < 0 || stream_type < 0) {
            return CreateErrorResponse(id, 400, "channel与stream_type必须为非负整数");
        }
    }

    auto &configManager = Common::ConfigManager::GetInstance();
    if (!configManager.SetConfig("/rtmp", params)) {
        EL_ERROR("保存RTMP配置失败");
        return CreateErrorResponse(id, 500, "保存RTMP配置失败");
    }

    return CreateSuccessResponse(id, nlohmann::json{{"status", "success"}});
}

// 获取RTMP运行状态（基础版）
nlohmann::json NetCommandHandler::HandleRTMPGetStatus(const std::string &id, const nlohmann::json &params)
{
    (void)params;
    EL_DEBUG("处理rtmp.getStatus请求");

    auto &configManager = Common::ConfigManager::GetInstance();
    nlohmann::json rtmp = configManager.GetConfig("/rtmp");
    nlohmann::json result;

    bool enabled = rtmp.is_object() ? rtmp.value("enabled", false) : false;
    result["enabled"] = enabled;

    // 基于配置返回基础状态；后续可对接实际推流状态
    result["sinks"] = nlohmann::json::array();
    if (rtmp.is_object() && rtmp.contains("sinks") && rtmp["sinks"].is_array()) {
        for (const auto &s : rtmp["sinks"]) {
            nlohmann::json st;
            st["enabled"] = s.value("enabled", false);
            st["url"] = s.value("url", "");
            st["channel"] = s.value("channel", 0);
            st["stream_type"] = s.value("stream_type", 0);
            st["state"] = st["enabled"].get<bool>() && enabled ? "unknown" : "disabled";
            result["sinks"].push_back(st);
        }
    }

    return CreateSuccessResponse(id, result);
}

namespace {
constexpr int kDefaultRtspPort = 554;

int ParsePortValue(const nlohmann::json &value)
{
    if (value.is_number_integer()) {
        return value.get<int>();
    }

    if (value.is_string()) {
        try {
            return std::stoi(value.get<std::string>());
        } catch (const std::exception &) {
            return -1;
        }
    }

    return -1;
}
} // namespace

nlohmann::json NetCommandHandler::HandleRTSPGetConfig(const std::string &id, const nlohmann::json &params)
{
    (void)params;
    EL_DEBUG("处理rtsp.getConfig请求");

    auto &configManager = Common::ConfigManager::GetInstance();
    nlohmann::json rtsp = configManager.GetConfig("/rtsp");

    bool enabled = true;
    int port = kDefaultRtspPort;

    if (rtsp.is_object()) {
        enabled = rtsp.value("enabled", true);
        if (rtsp.contains("port")) {
            int parsed = ParsePortValue(rtsp["port"]);
            if (parsed > 0 && parsed <= 65535) {
                port = parsed;
            }
        }
    }

    nlohmann::json result = {{"enabled", enabled}, {"port", port}};

    return CreateSuccessResponse(id, result);
}

nlohmann::json NetCommandHandler::HandleRTSPSetConfig(const std::string &id, const nlohmann::json &params)
{
    EL_DEBUG("处理rtsp.setConfig请求, 参数: {}", params.dump());

    if (!params.is_object()) {
        return CreateErrorResponse(id, 400, "参数必须为对象");
    }

    if (!params.contains("port")) {
        return CreateErrorResponse(id, 400, "缺少必要参数: port");
    }

    bool enabled = params.value("enabled", true);
    int port = ParsePortValue(params["port"]);

    if (port < 1 || port > 65535) {
        return CreateErrorResponse(id, 400, "端口号必须在1-65535之间");
    }

    nlohmann::json sanitized = {{"enabled", enabled}, {"port", port}};

    auto &configManager = Common::ConfigManager::GetInstance();
    if (!configManager.SetConfig("/rtsp", sanitized)) {
        EL_ERROR("保存RTSP配置失败");
        return CreateErrorResponse(id, 500, "保存RTSP配置失败");
    }

    return CreateSuccessResponse(id, nlohmann::json{{"status", "success"}});
}

} // namespace Protocol
} // namespace El
